/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 配送员设置
 *  */
import React, { Component } from 'react'
import PageHeaderLayout from "@/layouts/PageHeaderLayout"
import styles from "./style.less";
import { Form, Select, Button, Input, Popconfirm, Row, Col, message, Modal } from 'antd'
import { connect } from 'dva'
import StandardTable from '@/components/StandardTable'
import { debounce } from 'lodash'
import routerRedux from "umi/router"

const FormItem = Form.Item
const Option = Select.Option

@connect(({ loading, delieverSetting, station, operator }) => ({
  station,
  operator,
  delieverSetting,
  getList: loading.effects['delieverSetting/getSettingList']
}))
@Form.create()
export default class DistributorSetting extends Component {
  constructor(props) {
    super(props)
    this.state = {
      site_id: 'all',
      keywords: '',
      selectedRows: [],
      page: 1
    }
    this.columns = [
      {
        title: "编号",
        dataIndex: "courier_no",
        key: "courier_no",
        align: "center",
      },
      {
        title: "所属站点",
        dataIndex: "site_name",
        key: "site_name",
        align: "center",
        render:(text, record) => {
          const { station: { company_info={} },} = this.props
          return text ? text :( company_info && company_info.brand_name)
        }
      },
      {
        title: "配送员",
        align: "center",
        render: (text, record) => {
          return `${record.courier_name}-${record.courier_phone}`
        }
      },
      {
        title: "即时配送权限",
        align: "center",
        render: (record) => {
          return (
            <>
              <span style={{marginRight:20}}>{record.switch == '1' ? '已开启' : '已关闭'}</span>
              <Popconfirm
                placement="top"
                title={`确定${record.switch == '1' ? '关闭' : '开启'}该业务员的及时配送权限？`}
                onConfirm={() => this.handleOpenDelivery(record.courier_no, record.switch)}
                okText="确定"
                cancelText="取消"
              >
                <Button type='primary' size='small' > {record.switch == '1' ? '关闭' : '开启'} </Button>
              </Popconfirm>
            </>
          )
        }
      },

    ]
  }

  componentDidMount() {
    this.getList()
    this.getStationList(true) //防止下拉框每次下来带来不必要的渲染
  }

  getList = (_page) => {
    const { page } = this.state
    const { dispatch } = this.props
    this.getFormVlaues(res => {
      dispatch({
        type: 'delieverSetting/getSettingList',
        payload: {
          ...res,
          page: _page ? _page : page,
          size: 20
        }
      }).then(res=>{
        const { list } = res.data
        dispatch({
          type:"operator/updateState",
          payload:{
            list
          }
        })
      })
    })
  }

  onSubmit = debounce( e => {
    this.getList(1)
    this.setState({
      selectedRows: [],
      page: 1
    })
  }, 500, {
    leading: true,
    trailing: false
  });

  getFormVlaues = (then) => {
    const { form } = this.props
    const { validateFields } = form
    validateFields((err, fieldsValue) => {
      if (err) return
      let values = {...fieldsValue}
      if( !fieldsValue.site_id ){
        values.site_id = 'all'
      }
      this.setState({ fieldsValue:values })
      then(values)
    })
  }

  getStationList = (visible) => {
    const { dispatch } = this.props
    if (visible) {
      dispatch({
        type: "station/getStationList",
      });
    }
  }

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e, labe) => {
    this.setState({
      site_id: labe.props.value,
    })
  }

  changeSelect = (value) => {
    if (!value) {
      this.setState({
        site_id: "all",
      })
    }
  }

  onRowSelect = (selectedRows) => {
    this.setState({
      selectedRows,
    })
  }

  componentWillUnmount(){
    const { dispatch } = this.props
    dispatch({
      type:"operator/updateState",
      payload:{
        list: []
      }
    })
  }

  // 开通即时配送(老代码)
  handleOpenDelivery = (courier_no, onOff) => {
    const { dispatch } = this.props;

    const nextType = onOff == 1 ? 0 : 1;
    const payload = {
      courier_no,
      type: nextType
    };
    dispatch({
      type: "operator/deliveryStatus",
      payload,
      then: res => {
        const { code, msg } = res;
        let url, name;
        this.getList()
        if (code == 1094) {
          url = "/delivery/valuation";
          name = "配送费计价";
        } else if (code == 1095) {
          url = "/delivery/scope";
          name = "配送范围";
        } else if (code == 1096) {
          url = "/delivery/cost";
          name = "配送费结算规则";
        } else if (code != 0) {
          message.error(msg);
        }
        // code 1094-开启计价；1095-配送范围；1096-结算规则；1097-可开通
        if (url) {
          this.showConfirm({
            okText: "立即跳转",
            content: `${name}未设置，是否跳转到${name}界面设置`,
            onOk: () => {
              routerRedux.push({
                pathname: url
              });
            }
          });
        }
      }
    });
  };

  // 批量开通即时配送(老代码)
  handleOpenDeliveryBatch = (data, index, flag) => {
    const {
      dispatch,
    } = this.props;
    if (data == "") {
      message.error("请选择业务员");
      return;
    }
    this.currentCheckId = data.id;
    let payload = {
      courier_no: [],
      type:'1',
      switch: ""
    };
    if (Array.isArray(data)) {
      data.length > 0 &&
      data.map(item => {
        payload.courier_no.push(item.courier_no);
        if (flag) {
          payload.switch = 1;
        } else {
          payload.switch = 0;
        }
      });
    } else {
      let { switch: type, courier_no } = data;
      let nextType = type == 1 ? 0 : 1;
      payload = {
        courier_no,
        type:'1',
        switch: nextType
      };
    }
    if (payload.switch == 0) {
      this.switchDeliveryTypeBatch(payload);
      return;
    }

    /* 测试*/
    // payload.code = 1094;
    dispatch({
      type: "operator/quickStatus",
      payload,
      then: res => {
        const { code, msg } = res;
        const { operator: { list }} = this.props
        if (code != 0) {
          message.error(msg);
        } else if (code == 0) {
          this.setState({selectedRows:[]})
          this.getList()
          for (let i = 0, len = list.length; i < len; i++) {
            const selectedOperator = list[i];
            if (Array.isArray(data)) {
              data.length > 0 &&
              data.map(item => {
                if (selectedOperator.id == item.id) {
                  if (flag == true) {
                    list[i].switch = 1;
                  }
                }
              });
            }
          }
        }
      }
    });
  };

  // 批量触发开通(老代码)
  switchDeliveryTypeBatch = data => {
    const {
      dispatch,
      operator: { list }
    } = this.props;

    this.showConfirm({
      okText: "是",
      cancelText: "否",
      content: `是否${data.switch == 1 ? "开启" : "关闭"}该业务员的即时配送功能？`,
      onOk: () => {
        dispatch({
          type: "operator/quickStatus",
          payload: {
            ...data
          },
          then: res => {
            const { code,msg } = res;
            if (code == 0) {
              this.setState({selectedRows:[]})
              this.getList()
              for (let i = 0, len = list.length; i < len; i++) {
                const selectedOperator = list[i];
                if (Array.isArray(data.courier_no)) {
                  data.courier_no.length > 0 &&
                  data.courier_no.map(item => {
                    if (selectedOperator.courier_no == item) {
                        list[i].switch = 0;
                    }
                  });
                }
              }
            } else if (code != 0) {
              message.error(msg);
            }
          }
        });
      }
    });
  };

  handleTableChange = debounce(pagination => {
    this.setState({ page: pagination.current },()=>{
      this.getList()
    })
    this.setState({
      selectedRows: []
    })
  }, 500, {
    leading: true,
    trailing: false
  });

  showConfirm = params => {
    Modal.confirm({
      centered: true,
      okText: "确定",
      cancelText: "取消",
      title: "温馨提示",
      ...params
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      getList,
      delieverSetting: { deliveryList },
      station: { list=[], company_info={} },
    } = this.props
    const {
      site_id,
      keywords,
      selectedRows
    } = this.state
    return (
      <PageHeaderLayout title="配送员设置">
        <div className={styles.main}>
          <Form layout="inline" style={{ marginBottom: "24px" }}>
            <FormItem label="公司站点">
              {
                getFieldDecorator("site_id", {
                  initialValue: site_id
                })(
                  <Select
                    filterOption={this.onFilterOperator}
                    placeholder="选择站点"
                    showSearch
                    allowClear
                    style={{ width: "250px" }}
                    onSelect={this.selectCurrency}
                    onChange={this.changeSelect}
                  >                   
                    <Option key="all" value="all">
                      全部站点
                    </Option>
                    <Option key="0" value="0">
                      { company_info && company_info.brand_name}
                    </Option>
                    {
                      list && list.map(({ site_id, site_name }) => (
                        <Option key={`${site_id}`} value={site_id}>
                          {site_name}
                        </Option>
                      ))
                    }
                  </Select>
                )
              }
            </FormItem>
            <FormItem label="业务员">
              {
                getFieldDecorator("search", {
                  initialValue: keywords
                })(
                  <Input
                    allowClear
                    style={{ width: 250 }}
                    placeholder="请输入业务员姓名或手机号搜索"
                  />
                )
              }
            </FormItem>
            <FormItem>
              <Button type="primary" loading={getList} onClick={this.onSubmit}>查询</Button>
            </FormItem>
          </Form>
          <StandardTable
            loading={getList}
            columns={this.columns}
            data={deliveryList}
            rowKey={'id'}
            selectedRows={selectedRows}
            onSelectRow={this.onRowSelect}
            onChange={this.handleTableChange}
          />
          <Row type="flex" gutter={[20, 20]} style={{ margin: 0 }}>
            <Col><a onClick={this.handleOpenDeliveryBatch.bind(this, selectedRows, "", true)}>批量开启权限</a></Col>
            <Col><a onClick={this.handleOpenDeliveryBatch.bind(this, selectedRows, "", false)}>批量关闭权限</a></Col>
          </Row>
        </div>
      </PageHeaderLayout>
    )
  }
}
